import { FileEditorList } from "monaco-editor-solid";
import FS from "@isomorphic-git/lightning-fs";
import { BaseEditor, FileStore } from "../interface";
import { useSourceCodeStore } from "./useSourceCodeStore";
import { useContext } from "solid-js";
import { CodingSystemContext } from "../CodingApp";
export class TextEditor extends BaseEditor {
    constructor(public source: FileStore) {
        super();
    }
    getCode() {
        return "";
    }
    setCode(code: string) {}
}
/** 基于 Lightning-fs 的一个文件存储系统 */
export class LightningStore extends FileStore {
    constructor(public fs: FS) {
        super();
    }
    async getFile(path: string) {
        const res = await this.fs.promises.readFile(path);

        return new Blob([res]);
    }
    async getFileString(path: string) {
        const res = await this.fs.promises.readFile(path, "utf8");
        return res as string;
    }
    async setFile(path: string, val: Blob): Promise<void> {
        const buffer = await val.arrayBuffer();
        return this.fs.promises.writeFile(path, new Uint8Array(buffer));
    }
    async setFileString(path: string, val: string): Promise<void> {
        return this.fs.promises.writeFile(path, val);
    }
    moveFile(path: string, to: string): Promise<void> {
        return this.fs.promises.rename(path, to);
    }
    deleteFile(path: string): Promise<void> {
        return this.fs.promises.unlink(path);
    }
}

export const TextEditorComp = () => {
    const { fs, store, explorerVisible, editorOpenFile } =
        useContext(CodingSystemContext);
    const files = [
        // First Editor Show
        [],
    ];
    return (
        <FileEditorList
            toggleExplorer={(bool?: boolean) => {
                explorerVisible((i) => !i);
            }}
            // 直接通过 fs 写入了文件，所以不用担心
            fs={fs}
            files={files}
            expose={(data) => {
                // This Component expose some function to use
                editorOpenFile(() => {
                    return (path) => {
                        store.getFileString(path).then((code) => {
                            // 传递源代码交给编辑器
                            data.watchingEditor
                                .getWatching()
                                .openFile(path, code as string);
                        });
                    };
                });
            }}
        ></FileEditorList>
    );
};
